package com.ferry.serial.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;


/**
 * Created by daiyong
 */
public class SerializerFactory {
	Logger logger = LoggerFactory.getLogger(SerializerFactory.class);

	private static final Map<Integer, Serializer> serializerMap = new HashMap<>();

	static {
		ServiceLoader<Serializer> loaders = ServiceLoader.load(Serializer.class);
		Iterator<Serializer> iterator = loaders.iterator();
		while (iterator.hasNext()) {
			Serializer serializer = iterator.next();
			serializerMap.put(serializer.code(), serializer);
		}
	}

	public static Serializer getSerializer(int code) {
		Serializer serializer = serializerMap.get(code);

		if (serializer == null) {
			throw new IllegalArgumentException("没有找到对应的序列化类");
		}

		return serializer;
	}
}
